<template>
  <inline-Modal
    :visible="visible"
    title="查看"
    :showOk="false"
    @ok="handelOk()"
    @cancel="handelCancel()"
  >
    <div class="custom-page-container">
      <div class="header-search">
        <a-select
          showSearch
          allowClear
          :filter-option="filterOption"
          v-model="engineerType"
          placeholder="请选择工程类型"
          style="width: 200px"
          @change="getTreeParentData()"
        >
          <a-select-option
            :value="item.dicItemCode"
            v-for="item in engineerSoucre"
            :key="item.id"
          >
            {{ item.dicItemName }}
          </a-select-option>
        </a-select>
      </div>
      <div class="body-container ">
        <div class="left-tree">
          <div class="tree-container">
            <a-tree
              v-if="treeShow && treeData.length != 0"
              show-icon
              v-model="checkedKeys"
              :expanded-keys="expandedKeys"
              :selected-keys="selectedKeys"
              :auto-expand-parent="autoExpandParent"
              :tree-data="treeData"
              :replaceFields="{
                children: 'children',
                title: 'text',
                key: 'uuid',
              }"
              @expand="onExpand"
              @select="onSelect"
              :load-data="onLoadData"
            >
              <template slot="title" slot-scope="{ text, remark }">
                <div class="custom-tree-item" :title="text">
                  <div class="label">{{ text }}</div>
                  <div class="value">{{ remark }} 分</div>
                </div>
              </template>
              <!-- 文件夹图标 -->
              <template slot="custom" slot-scope="{ expanded, children }">
                <a-icon
                  :type="
                    children && children.length > 0
                      ? expanded
                        ? 'folder-open'
                        : 'folder'
                      : 'file'
                  "
                  :class="
                    children && children.length > 0
                      ? 'folder-icon'
                      : 'file-icon'
                  "
                />
              </template>
            </a-tree>
            <a-empty :image="simpleImage" v-else />
          </div>
        </div>
        <div class="right-table">
          <div class="table">
            <vxe-table
              ref="xTable"
              height="100%"
              border="inner"
              :data="tableData"
              :column-config="{ resizable: true }"
              size="small"
              :loading="loading"
            >
              <vxe-column
                field="assessmentContent"
                title="五级指标"
              ></vxe-column>
              <vxe-column field="determine" title="判定标准"></vxe-column>
              <vxe-column field="methods" title="审查资料及方式"></vxe-column>
              <!-- <vxe-column width="200" title="项目状态">
                <template #default="{ row }">
                  <a-select
                    v-if="row.proStatusDisabled"
                    showSearch
                    :filter-option="filterOption"
                    v-model="row.proStatus"
                    style="width: 100%"
                    placeholder="请选择"
                  >
                    <a-select-option
                      :value="item.dicItemCode"
                      v-for="item in proStatusSoucre"
                      :key="item.uuid"
                    >
                      {{ item.dicItemName }}
                    </a-select-option>
                  </a-select>
                  <span v-else>{{ row.proStatusDesc }}</span>
                </template>
              </vxe-column> -->
              <vxe-column
                field="singleScore"
                title="总分"
                width="100"
              ></vxe-column>
              <vxe-column title="责任主体" width="240">
                <template #default="{ row }">
                  <a-select
                    v-if="row.responsDisabled"
                    mode="multiple"
                    showSearch
                    :filter-option="filterOption"
                    :maxTagCount="2"
                    v-model="row.responsCode"
                    style="width: 100%"
                    placeholder="请选择"
                  >
                    <a-select-option
                      :value="item.dicItemCode"
                      v-for="item in responsiblSoucre"
                      :key="item.uuid"
                    >
                      {{ item.dicItemName }}
                    </a-select-option>
                  </a-select>
                  <span v-else>{{ row.responsibleSubjectDesc }}</span>
                </template>
              </vxe-column>
              <vxe-column
                field="operate"
                width="120"
                title="操作"
                fixed="right"
                align="left"
              >
                <template slot-scope="scope">
                  <div class="text-button-group">
                    <a-button
                      v-if="!scope.row.showButton"
                      type="link"
                      @click="edit(scope.row, scope.rowIndex)"
                    >
                      编辑
                    </a-button>
                    <a-button
                      v-if="scope.row.showButton"
                      type="link"
                      @click="onSubmit(scope.row, scope.rowIndex)"
                    >
                      确定
                    </a-button>
                    <a-button
                      v-if="scope.row.showButton"
                      type="link"
                      @click="cancel(scope.row, scope.rowIndex)"
                    >
                      取消
                    </a-button>
                  </div>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
          <!-- 分页 -->
          <div class="pager-container">
            <vxe-pager
              size="small"
              background
              :current-page.sync="pager.page"
              :page-size.sync="pager.pageSize"
              :total="pager.total"
              :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
              :page-sizes="[20, 50, 100, 500]"
              @page-change="paginationChange"
            >
              <template #left>
                <div class="vxe-pager-left-tip-container">
                  共<span>{{ pager.total }}</span
                  >条
                </div>
              </template>
            </vxe-pager>
          </div>
        </div>
      </div>
    </div>
  </inline-Modal>
</template>

<script>
import { addAttributeByKey } from "@/utils/index.js";
import { axios } from "@/utils/request";
import { Empty } from "ant-design-vue";
export default {
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    soucre: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getData();
        } else {
          this.reset();
        }
      },
      immediate: true,
    },
  },
  computed: {},
  data() {
    return {
      treeData: [],
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      currentNode: {},
      treeId: "",
      treeShow: false,
      //列表
      pager: {
        page: 1,
        pageSize: 20,
        total: 0,
      },
      tableData: [],
      loading: false,
      //项目状态
      proStatusSoucre: [],
      //责任主体
      responsiblSoucre: [],
      //工程类型
      engineerSoucre: [],
      engineerType: undefined,
    };
  },
  beforeCreate() {
    this.simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
  },
  mounted() {},
  methods: {
    //编辑
    edit(row, index) {
      this.tableData[index].responsDisabled = true;
      this.tableData[index].proStatusDisabled = true;
      this.tableData[index].showButton = true;
    },
    //取消
    cancel(row, index) {
      this.tableData[index].responsDisabled = false;
      this.tableData[index].proStatusDisabled = false;
      this.tableData[index].showButton = false;
    },
    //确定
    onSubmit(row) {
      let formJson = {
        uuid: row.uuid,
        proStatus: row?.proStatus,
        responsibleSubject: row?.responsCode.toString(),
      };
      //   if (!formJson.proStatus) {
      //     return this.$message.info("请选择项目状态", 1.5);
      //   } else
      if (!formJson.responsibleSubject) {
        return this.$message.info("请选择责任主体", 1.5);
      } else {
        axios
          .post(`/probusiness/qeEvaluationContent/update`, formJson, {
            headers: {
              "Content-Type": "application/json",
            },
          })
          .then((res) => {
            if (res.statusCode === 200 || res === 1) {
              this.$message.success("操作成功", 1.5);
              let { uuid } = this.currentNode;
              this.getTableData(uuid);
            } else {
              this.$message.error(res?.message ?? "操作失败");
            }
          })
          .catch((_) => {})
          .finally((_) => {});
      }
    },

    getData() {
      Promise.all([
        this.getEngineeringTypeList(),
        this.getProStatusList(),
        this.getResponsibleList(),
      ]).then(() => {
        this.getTreeParentData();
      });
    },
    //查询项目状态
    getProStatusList() {
      return new Promise((resolve, reject) => {
        this.$post("/system/dicSet/getDicItemByCode", {
          code: "proStatus",
        })
          .then((res) => {
            let { data } = res;
            this.proStatusSoucre = data || [];
            resolve();
          })
          .catch((_) => {
            this.proStatusSoucre = [];
            reject();
          })
          .finally((_) => {});
      });
    },
    //查询责任主体
    getResponsibleList() {
      return new Promise((resolve, reject) => {
        this.$post("/system/dicSet/getDicItemByCode", {
          code: "secType",
        })
          .then((res) => {
            let { data } = res;
            this.responsiblSoucre = data || [];
            resolve();
          })
          .catch((_) => {
            this.responsiblSoucre = [];
            reject();
          })
          .finally((_) => {});
      });
    },
    //查询工程类型
    getEngineeringTypeList() {
      return new Promise((resolve, reject) => {
        this.$post("/probusiness/qeModelEvaluation/getResponsibleList")
          .then((res) => {
            let { data } = res;
            this.engineerSoucre = data || [];
            resolve();
          })
          .catch((_) => {
            this.engineerSoucre = [];
            reject();
          })
          .finally((_) => {});
      });
    },

    getTreeParentData() {
      this.treeShow = false;
      return new Promise((resolve, reject) => {
        let { uuid } = this.soucre;
        let { engineerType = "" } = this;
        axios
          .get(
            `/probusiness/qeModelEvaluation/getFirstList?modelId=${uuid}&responsible=${engineerType}`,
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let { data } = res;
            this.treeData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              data,
              "children"
            );
            this.currentNode = this.treeData?.[0] ?? {};
            let firstId = this.treeData?.[0]?.uuid ?? "";
            if (!firstId) {
              return;
            }
            this.expandedKeys = [firstId];
            this.checkedKeys = [firstId];
            this.selectedKeys = [firstId];
            this.getTableData(firstId);
            resolve();
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {
            this.treeShow = true;
          });
      });
    },
    onLoadData(treeNode) {
      return new Promise((resolve, reject) => {
        let { uuid, levelId } = treeNode.dataRef;
        let { engineerType = "" } = this;
        axios
          .post(
            `/probusiness/qeModelEvaluation/getListByPid`,
            {
              levelId,
              type: "",
              pid: uuid,
              responsible: engineerType,
            },
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let { data } = res;
            let tree = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              data,
              "children"
            );
            treeNode.dataRef.children = tree ?? [];
            this.treeData = [...this.treeData];
            resolve();
          })
          .catch((_) => {
            reject();
          });
      });
    },
    getTableData(id = "") {
      if (!id) {
        return;
      }
      this.loading = true;
      return new Promise((resolve, reject) => {
        let { page, pageSize } = this.pager;
        let { engineerType = "" } = this;
        axios
          .post(
            `/probusiness/qeEvaluationContent/getPageSet?pageNo=${page}&pageSize=${pageSize}&sort=sort&order=asc`,
            {
              evaluationId: id,
              responsible: engineerType,
            },
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let list = res?.rows ?? [];
            list.forEach((item) => {
              //多选
              let codes = item?.responsibleSubject.split(",");
              this.$set(item, "responsCode", codes ?? []);
              //禁用状态
              this.$set(item, "responsDisabled", false);
              this.$set(item, "proStatusDisabled", false);
              //按钮
              this.$set(item, "showButton", false);
            });
            this.tableData = list;
            this.pager.total = res.totalCount ?? 0;
            resolve();
          })
          .catch((_) => {
            this.tableData = [];
            this.pager.total = 0;
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      let { uuid } = this.currentNode;
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData(uuid);
    },

    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    onSelect(expandedKeys, ev) {
      let { node } = ev;
      let { uuid = "" } = node?.dataRef || {};
      this.currentNode = node?.dataRef || {};
      this.checkedKeys = [uuid];
      this.selectedKeys = [uuid];
      this.pager.page = 1;
      this.getTableData(uuid);
    },
    reset() {
      this.autoExpandParent = false;
      this.treeData = [];
      this.expandedKeys = [];
      this.checkedKeys = [];
      this.selectedKeys = [];
      this.currentNode = [];
      this.tableData = [];
      this.pager = {
        page: 1,
        pageSize: 20,
        total: 0,
      };
    },

    handelOk() {
      this.$emit("ok");
    },
    handelCancel() {
      this.$emit("cancel");
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="less" scoped>
@primary-color: @primary-color;
.custom-page-container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  .header-search {
    display: flex;
    border-bottom: 2px solid @border-color;
    padding: 0 0 10px 0;
    /deep/.ant-select {
      margin-right: 16px;
    }
  }

  .body-container {
    flex: 1;
    display: flex;
    overflow: hidden;
    padding-top: 10px;
    .left-tree {
      width: 344px;
      flex-shrink: 0;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      border-right: 1px solid @border-color;
      .tree-container {
        flex: 1;
        overflow: auto;
        overflow: overlay;
        position: relative;
        /deep/.ant-empty {
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
        }
        /deep/.ant-tree {
          .ant-tree-node-content-wrapper {
            width: calc(100% - 34px);
            &.ant-tree-node-selected {
              background: #f5f7fc !important;
              color: @primary-color;
            }
            .folder-icon {
              color: #f5a623;
            }
            .file-icon {
              color: #54baff;
            }
            .ant-tree-title {
              width: calc(100% - 24px);
              display: inline-block;
              .custom-tree-item {
                display: flex;
                width: 100%;
                height: 100%;
                .label {
                  flex: 1;
                  overflow: hidden;
                  overflow: hidden;
                  white-space: nowrap;
                  text-overflow: ellipsis;
                  margin-right: 10px;
                }
                .value {
                  color: #525a5d;
                  span {
                    color: @primary-color;
                  }
                }
              }
            }
          }
        }
      }
    }
    .right-table {
      flex: 1;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      margin-left: 10px;
      .table {
        flex: 1;
        overflow: hidden;
      }
      .pager-container {
        padding-top: 10px;
        flex-shrink: 0;
      }
    }
  }
}
</style>
